/**
 * Copyright (c) 2007-2008 Nearchos Paspallis
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * AspectSense
 *
 * Middleware for annotation-based, context-aware and adaptive services for
 * mobile and ubiquitous computing
 *
 * This project is an open-source effort, initiated by Nearchos Paspallis as
 * part of his PhD work at the University of Cyprus (http://www.ucy.ac.cy).
 *
 * More information about the project is available at "http://aspectsense.org".
 */

package org.aspectsense.framework;

import static org.aspectsense.framework.ComponentLifecycleState.*;
import java.util.logging.Logger;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Field;

/**
 * <p/>
 * Date: Jul 13, 2007<br/>
 * Time: 8:38:27 AM
 * </p>
 *
 * @author Nearchos Paspallis [nearchos@cs.ucy.ac.cy]
 */
class ComponentContainer
{
    private static final Logger logger = Logger.getLogger(ComponentContainer.class.getCanonicalName());

    // a pointer to the pool which owns this container
    private final ComponentContainerPool componentContainerPool;

    // the enclosed component
    private Component component = null;

    private final String componentID;

    /**
     * The life-cycle state is automatically set by the constructor when it
     * instantiates the component.
     */
    private ComponentLifecycleState lifecycleState = ComponentLifecycleState.UNINSTANTIATED;

    ComponentContainer(final ComponentContainerPool componentContainerPool)
            throws ConfigurationException
    {
        super();

        if(componentContainerPool == null) throw new NullPointerException();

        this.componentContainerPool = componentContainerPool;

        componentID = componentContainerPool.getComponentMetadata().getComponentTypeCanonicalName();

        instantiateComponent();
    }

    /**
     * Getter method, provides access to the encapsulated component's
     * {@link ComponentLifecycleState}.
     *
     * @return an instance of {@link ComponentLifecycleState}
     */
    ComponentLifecycleState getComponentLifecycleState()
    {
        return lifecycleState;
    }

    private Component createComponentInstance()
            throws ConfigurationException
    {
        final Class componentType = componentContainerPool.getComponentType();

        logger.finest("Creating component with ID: " + componentID);

        try
        {
            return (Component) componentType.newInstance();
        }
        catch(IllegalAccessException iae)
        {
            throw new RuntimeException("Error while instantiating component of type: " + componentType, iae);
        }
        catch(InstantiationException ie)
        {
            throw new RuntimeException("Error while instantiating component of type: " + componentType, ie);
        }
        catch(ClassCastException cce)
        {
            throw new RuntimeException("Error while instantiating component of type: " + componentType, cce);
        }
    }

    // ------------------- Handling component lifecycle --------------------- //

    synchronized private void instantiateComponent()
            throws ConfigurationException
    {
        logger.finest("Instantiating component with ID: " + componentID);

        component = createComponentInstance();

        lifecycleState = UNINITIALIZED;
    }

    synchronized void initComponent()
            throws ConfigurationException
    {
        // lazy instantiation of the component
        if(lifecycleState == UNINSTANTIATED)
        {
            instantiateComponent();
        }

        if(lifecycleState != UNINITIALIZED && lifecycleState != SUSPENDED)
        {
            throw new ConfigurationException("Cannot init component while at state: " + lifecycleState);
        }

        logger.finest("Initializing component with ID: " + componentID);

        lifecycleState = INITIALIZING;

        component.init();

        lifecycleState = SUSPENDED;
    }

    synchronized void suspendComponent()
            throws ConfigurationException
    {
        if(lifecycleState != ACTIVATED)
        {
            throw new ConfigurationException("Cannot suspend component while at state: " + lifecycleState);
        }

        logger.finest("Suspending component with ID: " + componentID);

        lifecycleState = SUSPENDING;

        component.suspend();

        lifecycleState = SUSPENDED;
    }

    synchronized void activateComponent()
            throws ConfigurationException
    {
        if(lifecycleState != SUSPENDED)
        {
            throw new ConfigurationException("Cannot activate component while at state: " + lifecycleState);
        }

        logger.finest("Activating component with ID: " + componentID);

        lifecycleState = ACTIVATING;

        component.activate();

        lifecycleState = ACTIVATED;
    }

    synchronized void finitComponent()
            throws ConfigurationException
    {
        if(lifecycleState != SUSPENDED)
        {
            throw new ConfigurationException("Cannot finit component while at state: " + lifecycleState);
        }

        logger.finest("Finalizing component with ID: " + componentID);

        lifecycleState = FINALIZING;

        component.finit();

        lifecycleState = FINALIZED;
    }

    // ---------------- End of Handling component lifecycle ----------------- //

    public Class getProvidedServiceType()
    {
        return componentContainerPool.getProvidedServiceType();
    }

    private Map<Class, Field> componentFieldsByType = null;

    private Field getComponentFieldByType(final Class type)
    {
        if(type == null)
        {
            throw new NullPointerException("Illegal null argument!");
        }

        if(componentFieldsByType == null)
        {
            // late instantiation
            componentFieldsByType = new HashMap<Class, Field>();

            final Field [] declaredFields = component.getClass().getDeclaredFields();
            for(final Field declaredField : declaredFields)
            {
                final Class fieldType = declaredField.getType();
                componentFieldsByType.put(fieldType, declaredField);
            }
        }

        return componentFieldsByType.get(type);
    }

    synchronized void createLink(final ComponentContainer target)
            throws ConfigurationException
    {
        final Class targetComponentProvidedServiceType = target.getProvidedServiceType();

        // todo remove assumption that only one component of each type is referenced from within each component
        final Field field = getComponentFieldByType(targetComponentProvidedServiceType);
        field.setAccessible(true);

        try
        {
            field.set(component, target.component);
        }
        catch (IllegalAccessException iae)
        {
            throw new ConfigurationException("Could not create link: "
                    + componentContainerPool.getComponentType() + " -> "
                    + target.componentContainerPool.getComponentType());
        }
    }

    synchronized void destroyLink(final ComponentContainer target)
            throws ConfigurationException
    {
        final Class targetComponentProvidedServiceType = target.getProvidedServiceType();

        // todo remove assumption that only one component of each type is references from within each component
        final Field field = getComponentFieldByType(targetComponentProvidedServiceType);
        field.setAccessible(true);

        try
        {
            field.set(component, null);
        }
        catch (IllegalAccessException iae)
        {
            throw new ConfigurationException("Could not destroy link: "
                    + componentContainerPool.getComponentType() + " -> "
                    + target.componentContainerPool.getComponentType());
        }
    }

    public String toString()
    {
        final StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append("Component container [ID: ");
        stringBuilder.append(componentContainerPool.getComponentMetadata().getComponentTypeCanonicalName());
        stringBuilder.append(", component: ").append(component).append("]");

        return stringBuilder.toString();
    }
}